<?php

namespace App\System\Cis\Repositories;

use App\Exceptions\Customize\ParamsException;
use App\Module\Api\Controllers\Request\CurrencyConversionRequest;
use App\Module\Api\Controllers\Request\TableRequest;
use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Repositories\Repository;
use App\System\Cis\Model\CisUser;
use App\System\Cis\Services\DeclarationInputValidationService;
use App\System\Cis\Services\DeclarationStorageService;
use App\System\Coupon\Repositories\CouponUserRepository;
use App\System\Fina\Repositories\FinaIntegralRegRecordRepository;
use App\System\Log\Model\LogNumberChange;
use App\System\Log\Repositories\LogRepeatedEliminationRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;


class CisUserRepository extends Repository
{
    use SinglePattern;

    /**
     * 通过用户ID，及用户类型查询一条用户信息
     * @param $userId 用户ID
     * @param $userType 用户类型 1创客 2.城市合伙人
     * @return \Illuminate\Database\Eloquent\Model|null|static
     * @author liujun
     */
    public function getUser($userId,$userType=null)
    {
        return CisUser::where('id',$userId)
            ->when($userType, function ($query) use ($userType) {
                return $query->where('user_type',$userType);
            })
            ->first();
    }

    /**
     * 通过手机号查询主帐号信息
     * @param $mobile 手机号
     * @return \Illuminate\Database\Eloquent\Model|null|static
     * @author  liujun
     */
    public function getMasterUser($mobile)
    {
        return CisUser::where('mobile',$mobile)->where('parent_id',0)->first();
    }


    /**
     * 生成创客
     * @param array $user
     * @return int
     */
    public function CreateUser(array $user)
    {
        $res = CisUser::create($user);
        if(!$res)
        {
           return false;
        }
        return $res->id;
    }

    /**
     * 通过节点查找对应的创客
     * @param null $city_partner_id 城市合伙人ID
     * @param null $superior_maker_id 上级创客ID
     * @param null $user_area 区域
     * @return mixed
     * @author liujun
     */
    public function queryNodeUser($city_partner_id=null,$superior_maker_id=null,$user_area=null)
    {
        return CisUser::select('id','city_partner_id','superior_maker_id','referee_id')
            ->when($city_partner_id, function ($query) use ($city_partner_id) {
                return $query->where('city_partner_id',$city_partner_id);
            })
            ->when($superior_maker_id, function ($query) use ($superior_maker_id) {
                return $query->where('superior_maker_id',$superior_maker_id);
            })
            ->when($user_area, function ($query) use ($user_area) {
                return $query->where('user_area',$user_area);
            })
            ->first();
    }

    /**
     * 获取用户数量
     * @return mixed
     */
    public function getData(){
        $data['todayCount'] = CisUser::where('parent_id','!=',0)->where('created_at','>=',date('Y-m-d',time()))->count();
        $data['monthCount'] = CisUser::where('parent_id','!=',0)->where('created_at','>=',date('Y-m-01',time()))->count();
        return $data;
    }

    /**
     * 批量获取用户信息(包括删除的)
     * @param array $user_ids 用户数组ID
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getByInUser(array $user_ids)
    {
        return CisUser::withTrashed()->whereIn('id',$user_ids)->get();
    }

    /**
     * 用户数据字段，自增自减更新
     * @param integer $user_id 用户ID
     * @param integer $income 类型 1增加 2减少
     * @param integer $column 要变更字段名称
     * @param integer $value 变化的值
     * @return boolean
     */
    public function updateUserPurse($user_id,$income,$column,$value)
    {
        if($user_id && $income && $column && $value)
        {
            if($income == 1)
            {
                return CisUser::where('id',$user_id)->increment($column,$value);
            }
            else
            {
                return CisUser::where('id',$user_id)->decrement($column,$value);
            }
        }
        else
        {
            return false;
        }
    }

    /**
     * 获取列表
     * @param string $keyword
     * @param int $type 1 搜索手机号码 2 创客ID
     * @param bool $getall false：分页 true：不分页
     * @return mixed
     */
    public function getList($keyword='',$type=1,$getall=false)
    {
        if($getall){
            $data = CisUser::when($keyword,function ($query) use($keyword,$type){
                if($type==1){
                    return $query->where('mobile','like','%'.$keyword.'%');
                }else{
                    return $query->where('id','like','%'.$keyword.'%');
                }
            })
                ->orderBy('id','asc')
                ->where('parent_id','!=',0)
                ->get();
        }else{
            $data = CisUser::when($keyword,function ($query) use($keyword,$type){
                if($type==1){
                    return $query->where('mobile','like','%'.$keyword.'%');
                }else{
                    return $query->where('id','like','%'.$keyword.'%');
                }
            })
                ->orderBy('id','asc')
                ->where('parent_id','!=',0)
                ->paginate();
        }
        return $data;
    }

    /**
     * 编辑用户信息
     * @param $id
     * @param $updata
     * @return array|bool
     */
    public function updateData($id,$updata)
    {
        if(!$id){
            return false;
        }
        DB::beginTransaction();
        $user = CisUser::find($id);
        if($updata['status']){
            $user->status = $updata['status'];
        }
        if($updata['user_type']){
            $user->user_type = $updata['user_type'];
        }
        if($updata['user_renew'])
        {
           return $this->repeatedElimination($id);
        }
        $bool = $user->save($updata);
        if($bool){
            if($updata['status'])
            {
                if($user->superior_maker_ids)
                {
                    $input =  new DeclarationInputValidationService();
                    $declaration_storage = new DeclarationStorageService($input);
                    $res = $declaration_storage->externalUpdatePerformanceInterface($user->superior_maker_ids,$id,$updata['status']);
                    if($res)
                    {
                        return ['data' => $bool, 'message' => $res];
                    }
                }
            }
            DB::commit();
            $msg = '操作成功！';
        }else{
            $msg = '操作失败！';
        }
        return ['data' => $bool, 'message' => $msg];
    }

    /**
     * 查询创客的下级
     * @param int $id
     * @return array
     */
    public function getContection($id=0)
    {
        if($id){
            $info = CisUser::where('id',$id)->first();
        }else{
            $info = CisUser::where('id',1)->first();
        }
        $area_arr = [0=>'',1=>'创业区',2=>'创新区',3=>'创客区'];
        if($info){
            $data['id'] = $info->id;
            $data['name'] = $info->name;
            $data['user_area'] = $area_arr[$info->user_area];
            $data['entrepreneurship_achievement'] = (floor($info->entrepreneurship_achievement)/10000).'万';
            $data['chuangheng_achievement'] = (floor($info->chuangheng_achievement)/10000).'万';
            $data['director_achievement'] = (floor($info->director_achievement)/10000).'万';
            $data['repeated_consumption_date'] = $info->repeated_consumption_date;
            $data['created_at'] = $info->created_at;
            $data['children'] = [];
            $children = CisUser::where('superior_maker_id',$info->id)->orderBy('user_area')->get(['id','name','user_area','entrepreneurship_achievement','chuangheng_achievement','director_achievement','repeated_consumption_date','created_at']);
            if($children){
                foreach ($children as $ck=>$cv){
                    $data['children'][$ck]['id'] = $cv->id;
                    $data['children'][$ck]['name'] = $cv->name??'';
                    $data['children'][$ck]['user_area'] = $area_arr[$cv->user_area];
                    $data['children'][$ck]['entrepreneurship_achievement'] = (floor($cv->entrepreneurship_achievement)/10000).'万';
                    $data['children'][$ck]['chuangheng_achievement'] = (floor($cv->chuangheng_achievement)/10000).'万';
                    $data['children'][$ck]['director_achievement'] = (floor($cv->director_achievement)/10000).'万';
                    $data['children'][$ck]['repeated_consumption_date'] = $cv->repeated_consumption_date??'';
                    $data['children'][$ck]['created_at'] = is_object($cv->created_at)?$cv->created_at->toDateTimeString():$cv->created_at;
                    $data['children'][$ck]['children'] = CisUser::where('superior_maker_id',$cv->id)->count();
                }
            }
            return $data;
        }else{
            return ['data' => false, 'message' => '创客不存在！'];
        }
    }


    /**
     * 用户数据多字段，自增自减更新
     * @param $user_id 用户ID
     * @param $income  类型 1增加 2减少
     * @param array $column_value 字段值数组例：array('字段'=>'值')
     * @return bool
     * @author liujun
     */
    public function updateUserManyPurse($user_id,$income,array $column_value)
    {
        if($user_id && $income && $column_value)
        {
            $symbol = $income == 1 ? '+' : '-';
            $set = [];
            foreach ($column_value as $k=>$v)
            {
                if($v)
                {
                    $set[$k] = DB::raw("{$k}{$symbol}{$v}");
                }
            }
            if($set)
            {
                return CisUser::where('id',$user_id)->update($set);
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    /**
     * 用户登录
     * @param $mobile
     * @param $pwd
     * @return array
     */
    public function login($mobile,$pwd)
    {
        $userInfo = CisUser::where('mobile', $mobile)
            ->where('parent_id',0)
            ->first();
        if (empty($userInfo)) {
            return array('message' => '用户不存在', 'data' => '');
        }
        $password = $userInfo->password;
        if (Hash::check($pwd, $password)) {//密码是否正确
            Session::put('username', $userInfo->name);
            Session::put('userid', $userInfo->id);
            return array('message' => '登录成功', 'data' => $userInfo->id, 'status' => 'SUCCESS');
        } else {
            return array('message' => '密码不正确', 'data' => '');
        }
    }


    /**
     * 根据主帐号获取创客帐号列表
     * @param int $id
     * @return bool|\Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getChkList($id=0,$getall=false)
    {
        if(!$id){
            return false;
        }
        if($getall){
            $data = CisUser::where('parent_id',$id)->get();
        }else{
            $data = CisUser::where('parent_id',$id)->paginate();
        }
        return $data;
    }

    /**
     * 获取推荐列表
     * @param int $id
     * @return bool|\Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getRecommendList($id=0,$getall = false)
    {
        if(!$id){
            return false;
        }
        if($getall){
            return CisUser::where('referee_id',$id)->get();
        }else{
            return CisUser::where('referee_id',$id)->paginate();
        }
    }


    /**
     * 查询所有可以发工资的创客
     * @return array
     */
    public function getPaycheckUser()
    {
        $user_list = CisUser::select(['id','entrepreneurship_achievement as y','chuangheng_achievement as x','director_achievement as d','repeated_consumption_date as f'])
            ->where('entrepreneurship_achievement','>=',1000)
            ->where('chuangheng_achievement','>=',1000)
            ->where('status', 1)
            ->where('user_renew',1)
            ->where('repeated_consumption_date','>=',date("Y-m-d"))
            ->get()->toArray();
        return $user_list;
    }


    /**
     *更新用户信息
     */
    public function updateUser($set,$id)
    {
        if(!$id)
        {
            return false;
        }
        $res = CisUser::where('id',$id)->update($set);
        return $res;
    }

    /**
     * 后台转注册币
     * @param array $data
     * @return array
     */
    public function transferCoin(array $data)
    {
        DB::beginTransaction();
        $sender_id = $data['user_id'];  //转账人
        $sender_info = CisUser::find($sender_id);
        $receiver_id = $data['receiver'];   //接收人
        $receiver_info = CisUser::find($receiver_id);
        $cash = $data['coin_number'];
        $reason = $data['reasons'];
        $res1 = CisUser::where('id', $sender_id)->update(['registered_currency' => $sender_info->registered_currency - $cash]);
        $res2 = CisUser::where('id', $receiver_id)->update(['registered_currency' => $receiver_info->registered_currency + $cash]);
        $fina = FinaIntegralRegRecordRepository::getInstance();
        $sender_fina['income'] = 2;
        $sender_fina['type'] = 4;
        $sender_fina['record_type'] = 2;
        $sender_fina['cash'] = $cash;
        $sender_fina['after_cash'] = $sender_info->registered_currency - $cash;
        $sender_fina['commission'] = 0;
        $sender_fina['status'] = 1;
        $sender_fina['admin_id'] = Session::get('adminid');
        $sender_fina['user_id'] = $sender_id;
        $sender_fina['reasons'] = $reason;
        $res3 = $fina->createFina($sender_fina, $receiver_id);
        $receiver_fina['income'] = 1;
        $receiver_fina['type'] = 3;
        $receiver_fina['record_type'] = 2;
        $receiver_fina['cash'] = $cash;
        $receiver_fina['after_cash'] = $receiver_info->registered_currency + $cash;
        $receiver_fina['commission'] = 0;
        $receiver_fina['status'] = 1;
        $receiver_fina['admin_id'] = Session::get('adminid');
        $receiver_fina['user_id'] = $receiver_id;
        $receiver_fina['reasons'] = $reason;
        $res4 = $fina->createFina($receiver_fina, $sender_id);
        if ($res1 && $res2 && $res3 && $res4) {
            $bool = true;
            $message = '转账成功！';
            DB::commit();
        } else {
            $bool = false;
            $message = '转账失败！';
            DB::rollBack();
        }
        return ['data' => $bool, 'message' => $message];
    }

    /**
     * API获取我的帐号、我的用户列表
     * @param $request object
     * @param $parent_id
     */
    public function getUserList(TableRequest $request,$parent_id = 0,$referee_id = 0)
    {
        $data = CisUser::when($parent_id,function($query) use($parent_id){
            $query->where('parent_id',$parent_id);
            })
            ->when($referee_id,function($query) use($referee_id){
                return $query->where('referee_id',$referee_id);
            })
            ->orderBy($request->orderBy,$request->orderType)
            ->paginate($request->limit,['*'],'page',$request->page);
        foreach($data as $v) {
            $item = [];
            $item['id'] = $v->id;
            $item['status'] = $v->status;
            $item['name'] = $v->name;
            $item['imagePath'] = $v->head_image_path;
            $item['userType'] = $v->user_type;
            $item['entrepreneurshipAchievement'] = $v->entrepreneurship_achievement;
            $item['chuanghengAchievement'] = $v->chuangheng_achievement;
            $item['directorAchievement'] = $v->director_achievement;
            $item['integral'] = $v->integral;
            $item['registeredCurrency'] = $v->registered_currency;
            $item['mobile'] = $v->mobile;
            $item['userNumber'] = $v->total_users_number;
            $item['timestamp'] = $v->created_at->toDateTimeString();
            $return['users'][] = $item;
        }
        $return['total'] =$data->total();
        return $return;
    }

    /**
     * 查询当前用户网体下直推数(只适全于发工资服务类使用，其它地方请勿使用)
     * @param $user_id 当前用户ID
     */
    public function findRecommendedNumber($user_id)
    {
        if(!$user_id)
        {
            return false;
        }

        $user_info = CisUser::where('superior_maker_id',$user_id)
            ->orderBy('user_area')
            ->get();//查找此用户下一级创客,按区域排序
        if(!$user_info)
        {
            return false;
        }
        $number = 1;//默认创新区推人数为1；
        foreach ($user_info as $v)
        {
            if($v->referee_id == $user_id && $v->user_area == 1) $number++;//如果是创业区的，并且推荐人是当前用户，则加1的直推用户数
            $superior_maker_ids = $v->superior_maker_ids.','.$v->id;
            $user_list = CisUser::where('referee_id',$user_id)
                ->where(function($query)use ($user_id,$superior_maker_ids){
                    $query->where('superior_maker_ids','like',$superior_maker_ids.',%')
                        ->orwhere("superior_maker_ids",$superior_maker_ids);
                })
                ->get();
            if($number == 1 && $user_list->count() == 0)
            {//创业区没有推荐过人
                return false;
            }
            $number += $user_list->count();
            if($number >= 3)
            {//创业区推荐数大于两个直接返回成功
                return true;
            }
        }
        return false;
    }

    /**
     * 清除测试环境账号
     */
    public function deleteUser()
    {
        $user_list = CisUser::select(['id','superior_maker_ids'])
        ->where('superior_maker_ids','like','1,3,%')
        ->orWhere('superior_maker_ids','1,3')->get();
        $fina = FinaIntegralRegRecordRepository::getInstance();
        $coupon = CouponUserRepository::getInstance();
        foreach ($user_list as $v)
        {
            $fina->deleteFina($v->id);
            $coupon->deleteCoupon($v->id);
            CisUser::where('id',$v->id)->forceDelete();
        }
        $this->updateUser(['integral'=>0,'freeze_integral'=>0,'registered_currency'=>0,'freeze_registered_currency'=>0,'total_users_number'=>0,'recommend_number'=>0,'entrepreneurship_achievement'=>0,'chuangheng_achievement'=>0,'director_achievement'=>0],3);
        $fina->deleteFina(3);
        $coupon->deleteCoupon(3);
    }

    /**
     * 转移创客帐号
     * @param array $data
     * @return array
     */
    public function transferAccount(array $data)
    {
        $refer = CisUser::where('mobile',$data['mobile'])->where('parent_id',0)->first();
        $userId = Session::get('userid');
        if(!$refer){
            $newData['mobile'] = $data['mobile'];
            $newData['password'] = bcrypt($data['mobile']);
            $res = CisUser::create($newData);
            if($res){
                $referId = $res->id;
            }else{
                return ['data'=>'操作失败','s'=>'FAIL'];
            }
        }else{
            if($refer->id == $userId){
                return ['data'=>'接收人为本人','s'=>'FAIL'];
            }
            $referId = $refer->id;
        }
        $userInfo = CisUser::find($userId);
        if (Hash::check($data['password'], $userInfo->password)) {//密码是否正确
            DB::beginTransaction();
            $res = true;
            $bool1 = CisUser::where('id',$data['id'])->update(['parent_id'=>$referId,'mobile'=>$data['mobile']]);
            $log['transferor_id'] = $userId;
            $log['transferor_son_id'] = $data['id'];
            $log['receiver_id'] = $referId;
            $bool2 = LogNumberChange::create($log);
            if(!$bool1 || !$bool2){
                $res = false;
            }
            if($res){
                DB::commit();
                return ['data'=>'操作成功','s'=>'SUCCESS'];
            }else{
                DB::rollBack();
                return ['data'=>'操作失败','s'=>'FAIL'];
            }
        } else {
            return ['data'=>'登录密码错误','s'=>'FAIL'];
        }
    }

    /**
     * 修改密码
     * @param array $data
     * @return array
     */
    public function changePwd(array $data)
    {
        $user = CisUser::where('mobile',$data['mobile'])->where('parent_id',0)->first();
        if(!$user){
            return ['data'=>'用户不存在','s'=>'FAIL'];
        }
        if($data['pwd_new'] != $data['pwd_confirm']){
            return ['data'=>'两次输入的新密码不一致','s'=>'FAIL'];
        }
        if (Hash::check($data['pwd_old'], $user->password)) {//密码是否正确
            $res = CisUser::where('id',$user->id)->update(['password'=>bcrypt($data['pwd_new'])]);
            if(!$res){
                return ['data'=>'操作失败','s'=>'FAIL'];
            }else{
                return ['s'=>'SUCCESS'];
            }
        } else {
            return ['data'=>'原密码不正确','s'=>'FAIL'];
        }
    }

    /**
     * 用户积分转注册币
     * @param CurrencyConversionRequest $currencyConversionRequest
     * @param $user_id 用户ID
     */
    public function conversion(CurrencyConversionRequest $currencyConversionRequest ,$user_id)
    {
        DB::beginTransaction();
        $user_info = $this->getUser($user_id);
        $cash = $currencyConversionRequest->number;
        if($user_info->integral < $cash) return ['s'=>'10000','d'=>'转换失败，积分不足'];
        $fina = FinaIntegralRegRecordRepository::getInstance();
        $after_cash = $user_info->integral - $cash;
        $data = ['income'=>2,'type'=>10,'record_type'=>1,'cash'=>$cash,'after_cash'=>$after_cash,'status'=>1,'user_id'=>$user_id,'commission'=>0];
        $res_one = $fina->createFina($data);//生成扣积分记录
        $data['income'] = 1;
        $data['record_type'] = 2;
        $data['after_cash'] = $user_info->registered_currency + $cash;
        $res_two = $fina->createFina($data);//生成加注册币记录

        $res_three = $this->updateUserPurse($user_id,2,'integral',$cash);
        $res_four = $this->updateUserPurse($user_id,1,'registered_currency',$cash);
        if(!$res_one || !$res_two || !$res_three || !$res_four) return ['s'=>'10000','d'=>'转换失败，服务器数据异常'];
        DB::commit();
        return ['s'=>'0','d'=>'操作成功'];
    }

    /**
     * 获取所有业绩大于1000用户
     * @return array
     */
    public function getPerformanceUser()
    {
        $user_list = CisUser::select(['id','entrepreneurship_achievement as y','chuangheng_achievement as x','director_achievement as d','repeated_consumption_date as f'])
            ->where('entrepreneurship_achievement','>=',1000)
            ->where('chuangheng_achievement','>=',1000)
            ->get()->toArray();
        return $user_list;
    }

    /**
     * 验证用户的支付密码是否准确
     * @param $id
     * @param $payPassword
     */
    public function checkPayPassword($id,$payPassword)
    {
        return CisUser::where('id',$id)->where('pay_password',$payPassword)->first();
    }

    /**
     * 更新创客手机号
     * @param $master_id
     */
    public function updateMobile($master_id,$mobile)
    {
        if(!$master_id)
        {
            return false;
        }
        $res_one = CisUser::where('parent_id',$master_id)->update(['mobile'=>$mobile]);
        $res_two = CisUser::where('id',$master_id)->update(['mobile'=>$mobile]);
        if($res_one && $res_two)
        {
            return true;
        }
        return false;
    }

    /**
     * 通过复销日期查询对应的用户
     * @param $type 1查询3天到复销日期的用户 2查询超过87天复销日期用户 3查询过期一天复销用户 4查询过期90天用户
     */
    public function findRepeatedElimination($type)
    {
        switch ($type)
        {
            case 1:
                $end_time = date("Y-m-d",strtotime("+3 day"));
                $start_time = date("Y-m-d");
                return CisUser::select(['id','mobile','superior_maker_ids','entrepreneurship_achievement as y','chuangheng_achievement as x','director_achievement as d','repeated_consumption_date','user_area'])
                    ->whereBetween("repeated_consumption_date",[$start_time,$end_time])
                    ->get();
                break;
            case 2:
                $end_time = date("Y-m-d",strtotime("-87 day"));
                $start_time = date("Y-m-d",strtotime("-90 day"));
                return CisUser::select(['id','mobile','superior_maker_ids','entrepreneurship_achievement as y','chuangheng_achievement as x','director_achievement as d','repeated_consumption_date','user_area'])
                    ->whereBetween("repeated_consumption_date",[$start_time,$end_time])
                    ->get();
                break;
            case 3:
                $time = date("Y-m-d",strtotime("-1 day"));
                return CisUser::select(['id','mobile','superior_maker_ids','entrepreneurship_achievement as y','chuangheng_achievement as x','director_achievement as d','repeated_consumption_date','user_area'])
                    ->where("repeated_consumption_date",$time)
                    ->get();
                break;
            case 4:
                $time = date("Y-m-d",strtotime("-91 day"));
                return CisUser::select(['id','mobile','superior_maker_ids','entrepreneurship_achievement as y','chuangheng_achievement as x','director_achievement as d','repeated_consumption_date','user_area'])
                    ->where("repeated_consumption_date",$time)
                    ->get();
                break;
            default:
                break;
        }
        return false;
    }

    /**
     * 根据IDS查询可以发工资的创客
     * @return array
     */
    public function getPaycheckUserByIds($ids)
    {
        $user_list = CisUser::select(['id','mobile'])
            ->where('status', 1)
            ->where('user_renew',1)
            ->where('repeated_consumption_date','>=',date("Y-m-d"))
            ->orderBy('id','desc')
            ->get()->toArray();
        return $user_list;
    }

    /**
     * 创客复消
     * @param $user_id 用户ID
     */
    public function repeatedElimination($user_id)
    {
        $user_info = $this->getUser($user_id);
        if($user_info->repeated_consumption_date)
        {//有复销日期，即已发过工资的才执行复销业务
            if($user_info->integral < 1000)
            {
                return [
                    'data' => 0,
                    'message'    => '复消失败，积分不足1000',
                ];
            }
            $res = $this->updateUserPurse($user_id,2,'integral',1000);//先扣钱
            if(!$res)
            {
                return [
                    'data' => 0,
                    'message'    => '复消失败，扣款失败',
                ];

            }
            $fina_set = ['income'=>2,
                         'type'=>13,
                         'record_type'=>1,
                         'cash'=>1000,
                         'after_cash'=>$user_info->integral - 1000,
                         'commission'=>0,
                         'status'=>1,
                         'user_id'=>$user_id];
            $fina = FinaIntegralRegRecordRepository::getInstance();
            $res = $fina->createFina($fina_set,$user_id);//生成扣款记录
            if(!$res)
            {
                return [
                    'data' => 0,
                    'message'    => '复消失败，服务内部异常',
                ];
            }

            $couponUser = CouponUserRepository::getInstance();
            $set = ['amount'=>1000,
                    'expire_time'=>date("Y-m-d H:i:s",strtotime("+30 day")),
                    'user_id'=>$user_id,
                    'status'=>0
            ];
            $id = $couponUser->createCoupon($set);//生成购物券
            if(!$id)
            {
                return [
                    'data' => 0,
                    'message'    => '复消失败，服务内部异常',
                ];
            }
            if($user_info->repeated_consumption_date < date("Y-m-d"))
            {
                $expiry_time = date("Y-m-d",strtotime("+30 day"));
            }
            else
            {
                $expiry_time = date("Y-m-d",strtotime("+30 day",strtotime($user_info->repeated_consumption_date)));
            }
            $log_repeated = LogRepeatedEliminationRepository::getInstance();
            $data = ['amount'=>1000,'user_id'=>$user_info->id,'expiry_time'=>$expiry_time];
            $res = $log_repeated->addData($data);//新增一条复销记录
            if(!$res)
            {
                return [
                    'data' => 0,
                    'message'    => '复消失败，服务内部异常',
                ];
            }

            $res = $this->updateUser(['repeated_consumption_date'=>$expiry_time],$user_info->id);//更新复销日期
            if(!$res)
            {
                return [
                    'data' => 0,
                    'message'    => '复消失败，服务内部异常',
                ];
            }
            DB::commit();
            return [
                'data' => 1,
                'message' => '操作成功'
            ];

            //返回被扣除的业绩 @todo

        }
        else
        {
            return [
                'data' => 0,
                'message'    => '复消失败，未达复消条件',
            ];
        }
    }

}